package jfupdater.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Comparator;

public class SysUtils {

	private static final String SYS_PROP_MOD_VERSION = "ro.modversion";
	private static final int PROP_MOD_VERSION_SKIP_CHARS = 3;

	public static String getSystemProperty(String propName) {
		String line;
		BufferedReader input = null;
        try {
        	Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
        	return null;
        } finally {
        	if(input != null) {
				try {
					input.close();
				} catch (IOException e) { }
        	}
        }

         return line;
	}
	
	/**
	 * 
	 * @return the system mod version or a int[0] if the property is not found or not parseable
	 */
	public static int[] getSystemModVersion() {
		String modVersion = getSystemProperty(SYS_PROP_MOD_VERSION);
		
		if(modVersion == null || modVersion.length() < PROP_MOD_VERSION_SKIP_CHARS) return new int[0];
		
		String version[] = modVersion.substring(PROP_MOD_VERSION_SKIP_CHARS).split("\\.");
		
		int[] retValue = new int[version.length];
		try {
			for(int i = 0; i < version.length; i++) {
				retValue[i] = Integer.parseInt(version[i]);
			}
		} catch (NumberFormatException e) {
			return new int[0];
		}

		return retValue;
	}
	
	public static final Comparator<int[]> VERSION_COMPARATOR = new Comparator<int[]>() {

		@Override
		public int compare(int[] a, int[] b) {
			int max = Math.min(a.length, b.length);
			for(int i = 0; i< max; i++) {
				if(a[i] != b[i])
					return a[i] - b[i];
			}
			
			if (a.length != b.length) return a.length - b.length;
			else return 0;
		}
		
	};
}
